<?php
/**
 * Created by PhpStorm.
 * Author: D H
 * Date: 2017/6/16
 * Time: 17:26
 */
namespace app\api\logic;
use think\Db;
use think\response\View;
use tool\Common;

class Article extends Base{
    //根据新闻类型ID得到新闻列表
    public function getArticleListByTypeID(){
        //测试数据
       /* $arr = '{
             "typeID": 2
        }';
        $data = json_decode($arr,true);*/
       $data = $this->data;
        $list = Db::name('article')->where('typeID',$data['typeID'])
            ->where('status',1)
            ->select();
        $new_list = [];
        $arr = [];
        foreach ($list as $k => $val){
            $new_list[$k]['articleID']  = $val['id'];
            $new_list[$k]['thumb']  = $val['thumb'];
            $new_list[$k]['releaseTime']  = date('Y-m-d H:i:s',$val['addtime']);
            $new_list[$k]['title']  = $val['title'];
            $arr[$k] = $val['id'];
        }
        $_list = Db::name('article_comments')->where('articleID','in',$arr)->select();
        if ($_list){
            foreach ($new_list as $k => $val){
                foreach ($_list as $key => $value){
                    if ($val['articleID'] == $value['articleID']){
                        $new_list[$k]['comments'][] = $value;
                    }
                }
            }
            foreach ($new_list as $k => $val){
                $new_list[$k]['total'] = count($val['comments']);
                unset($new_list[$k]['comments']);
            }
        }else{
            foreach ($new_list as $k => $val){
                $new_list[$k]['total'] = 0;
                //unset($new_list[$k]['comments']);
            }
        }

        //return $new_list;
        return Common::rm(1,'操作成功',['articleList' => $new_list]);
    }

    //根据新闻ID得到新闻详细信息
    public function getArticleMsgByArticleID(){
        $data = $this->data;
        //查询新闻详情
        $new_arr = Db::view('article',['introduce','addtime','title','past','pastc','hit'])
            ->view('article_content','content','article_content.articleID = article.id')
            ->where('article.id',$data['articleID'])
            ->find();
        $_new_arr = json_decode($new_arr['content'],true);
        $_arr['img'] = $_new_arr['img'];
        if (!empty( $_new_arr['video']['videoURL'])){
            $_list['exist'] = 1;
            $_list['videoURL'] = $_new_arr['video']['videoURL'];
            $_list['videoPhoto'] = $_new_arr['video']['videoPhoto'];
            $_list['videoText'] = $_new_arr['video']['text'];
            unset($new_arr['content']);
        }else{
            $_list['exist'] = 0;
            $_list['videoURL'] = '';
            $_list['videoPhoto'] = '';
            $_list['videoText'] = '';
            unset($new_arr['content']);
        }
        $past = [];
        if (!empty($new_arr['past'])){
            $a = explode(',',$new_arr['past']);
            foreach ($a as $k => $val){
                if ($val == $this->getUserID()){
                    $past['past'] = 1;
                    break;
                }else{
                    $past['past'] = 0;     //如果past不为空 并且past！= $this->getUserID()
                }
            }
        }else{
            $past['past'] = 0;
        }
        if (!empty($new_arr['pastc'])){
            $a = explode(',',$new_arr['pastc']);
            foreach ($a as $k => $val){
                if ($val == $this->getUserID()){
                    $past['pastc'] = 1;
                    break;
                }else{
                    $past['pastc'] = 0;     //如果past不为空 并且past！= $this->getUserID()
                }
            }
        }else{
            $past['pastc'] = 0;
        }
        $array = [
            'title' =>  $new_arr['title'],
            'introduce' =>  $new_arr['introduce'],
            'addtime' => date('Y-m-d H:i:s',$new_arr['addtime']),
            'result' => $_arr,
            'exist' =>  $_list['exist'],
            'past' =>  $past['past'],
            'pastc' =>  $past['pastc'],
            'videoURL' =>  $_list['videoURL'],
            'videoPhoto' =>  $_list['videoPhoto'],
            'videoText' =>  $_list['videoText']
        ];
        Db::name('article')->where('id',$data['articleID'])->update(['hit' => $new_arr['hit']+1]);
        return Common::rm(1,'操作成功',$array);
    }

    //发表评论
    public function publishComments(){
        //测试数据
        /*$arr = '{
            "articleID": 2,
            "content":"小编说的有道理"
        }';
        $data = json_decode($arr,true);*/
       // $user = ['userID' => 3];               //得到登录用户
        $data = $this->data;
        $new_data = [
            'addtime' => THINK_START_TIME,
            'parentID' => $data['contentID'],
            'userID' => $this->getUserID(),
            'articleID' => $data['articleID'],
            'content' => $data['content'],
            'sendUserID' => $data['sendUserID'],
        ];
        $id = Db::name('article_comments')->insertGetId($new_data);
        if ($id){
            return Common::rm(1,'操作成功');
        }
    }

    //根据新闻ID得到评论
    public function getCommentsByArticleID(){
        //得到新闻评论(10条)
        $userID = $this->getUserID();
        $list = Db::view('article_comments',['id' => 'contentID','content','addtime','praise','past'])
            ->view('operator',['id' => 'userID','name' => 'userName','photo' => 'thumb'],'operator.id = article_comments.userID')
            ->where('article_comments.articleID',$this->data['articleID'])
            ->where('parentID',0)
            ->limit(10)
            ->order('addtime desc')
            ->select();
        $result = [];
        if ($list){
            foreach ($list as $k => $val){
                $result[$k]['userID'] = $val['userID'];
                $result[$k]['name'] = $val['userName'];
                $result[$k]['content'] = $val['content'];
                $result[$k]['contentID'] = $val['contentID'];
                $result[$k]['praise'] = $val['praise'];
                $result[$k]['thumb'] = $val['thumb'];
                $result[$k]['addtime'] = date('Y-m-d H:i',$val['addtime']);
                if (!empty($val['past'])){
                    //用户已经对该评论点赞
                    $a = explode(',',$val['past']);
                    foreach ($a as $key => $value){
                        if ($value == $userID){
                            $result[$k]['past'] = 1;
                            break;
                        }else{
                            $result[$k]['past'] = 0;
                        }
                    }
                }else{
                    //用户未对该评论点赞
                    $result[$k]['past'] = 0;
                }
            }
            return Common::rm(1,'操作成功',['commentsList' => array_reverse($result)]);
        }else{
            return Common::rm(-2,'客官暂时还没有任何评论哟');
        }
    }

    //得到更多评论
    public function getMoreComments(){
        $data = $this->data;
        $list = Db::view('article_comments',['id' => 'contentID','content','addtime','praise','past'])
            ->view('operator',['id' => 'userID','name' => 'userName','photo' => 'thumb'],'operator.id = article_comments.userID')
            ->where('article_comments.articleID',$this->data['articleID'])
            ->where('parentID',0)
           ->limit(($data['startPoint'] - 1) * $data['several'], $data['several'])
            ->order('addtime desc')
            ->select();
        $result = [];
        if ($list){
            foreach ($list as $k => $val){
                $result[$k]['userID'] = $val['userID'];
                $result[$k]['name'] = $val['userName'];
                $result[$k]['content'] = $val['content'];
                $result[$k]['contentID'] = $val['contentID'];
                $result[$k]['praise'] = $val['praise'];
                $result[$k]['thumb'] = $val['thumb'];
                $result[$k]['addtime'] = date('Y-m-d H:i',$val['addtime']);
                if (!empty($val['past'])){
                    //用户已经对该评论点赞
                    $a = explode(',',$val['past']);
                    foreach ($a as $key => $value){
                        if ($value == $this->getUserID()){
                            $result[$k]['past'] = 1;
                            break;
                        }else{
                            $result[$k]['past'] = 0;     //如果past不为空 并且past！= $this->getUserID()
                        }
                    }
                }else{
                    //用户未对该评论点赞
                    $result[$k]['past'] = 0;
                }
            }
            return Common::rm(1,'操作成功',['commentsList' => array_reverse($result)]);
        }else{
            return Common::rm(-2,'客官暂时还没有任何评论哟');
        }
    }

    //得到回复
    public function getReply(){
        $data = $this->data;
        $list = Db::view('article_comments','content,addtime,praise')
            ->view('operator',['id' => 'sendUserID','name' => 'sendUserName','photo' => 'thumb'],'operator.id = article_comments.userID')
            ->view(['a_operator' => 'operators'],['id' => 'userID','name' => 'userName'],'operators.id = article_comments.sendUserID')
            ->where('article_comments.articleID',$data['articleID'])
            ->where('article_comments.parentID',$data['contentID'])
            ->order('addtime')
            ->select();
        if ($list){
            $result = [];
            foreach ($list as $k => $val){
                $result[$k]['name'] = $val['sendUserName'].'回复'.$val['userName'];
                $result[$k]['content'] = $val['content'];
                $result[$k]['thumb'] = $val['thumb'];
                $result[$k]['addtime'] = date('Y-m-d H:i',$val['addtime']);
            }
            return Common::rm(1,'操作成功',['replyList' => $result]);
        }else{
            return Common::rm(-2,'客官暂时还没有任何回复哟');
        }

    }

    //新闻评论点赞
    public function thumbUpArticle(){
        $data =$this->data;
        $exist = Db::name('article_comments')->where('articleID',$data['articleID'])->where('id',$data['contentID'])->find();
        if (!empty($exist['past'])){
            //用户已经对该评论点赞
            $a = explode(',',$exist['past']);
            foreach ($a as $key => $value){
                if ($value == $this->getUserID()){
                    return Common::rm(-2,'请不要重复点赞');
                }
            }
        }
        $num = DB::view('article_comments','praise,past')->where('articleID',$data['articleID'])->where('id',$data['contentID'])->find();
        if (!$num){
            return Common::rm(-2,'操作失败');
        }
        if ($num['past']){
            $praise = [
                'praise' => $num['praise'] +1,
                'past' => $num['past'].','.$this->getUserID()
            ];
        }else{
            $praise = [
                'praise' => $num['praise'] +1,
                'past' =>$this->getUserID()
            ];
        }
        Db::name('article_comments')->where('id',$data['contentID'])->where('articleID',$data['articleID'])->update($praise);
        return Common::rm(1,'操作成功');
    }

    //取消新闻评论点赞
    public function cancelArticle(){
        $data =$this->data;
        $num = DB::view('article_comments','praise,past')->where('articleID',$data['articleID'])->where('id',$data['contentID'])->find();
        if (!$num){
            return Common::rm(-2,'操作失败');
        }
        $a = explode(',',$num['past']);
        foreach ($a as $k => $val){
            if ($val == $this->getUserID()){
                unset($a[$k]);
            }
        }
        $praise = [
            'praise' => $num['praise'] -1,
            'past' =>implode(',',$a)
        ];
        Db::name('article_comments')->where('id',$data['contentID'])->where('articleID',$data['articleID'])->update($praise);
        return Common::rm(1,'操作成功');
    }

    //得到视频列表
    public function getVideoList(){
        $list = Db::view('video',['id' => 'vID','title','addtime','hit','thumb'])
            ->view('video_type','name','video.typeID = video_type.id')
            ->select();
        foreach ($list as $k => $val){
            $list[$k]['addtime'] = date('Y-m-d H:i',$val['addtime']);
        }
        return Common::rm(1,'操作成功',['list' => $list]);
    }

    //根据视频ID得到视频详情
    public function getVideoByVID(){
        $str = Db::name('video')->where('id',$this->data['vID'])->find();
        $hit = $str['hit'];
       //* return $hit;
        Db::table('a_video')->where('id',$this->data['vID'])->update(['hit' => $hit + 1]);
        return Common::rm(1,'操作成功',['str' => $str['address']]);
    }

    //新闻点赞
    public function thumbUp(){
        $data =$this->data;
        $exist = Db::name('article')->where('id',$data['articleID'])->find();
        if (!empty($exist['past'])){
            //用户已经对该评论点赞
            $a = explode(',',$exist['past']);
            foreach ($a as $key => $value){
                if ($value == $this->getUserID()){
                    return Common::rm(-2,'请不要重复点赞');
                }
            }
        }
        $num = DB::view('article','praise,past')->where('id',$data['articleID'])->find();
        if (!$num){
            return Common::rm(-2,'操作失败');
        }
        if ($num['past']){
            $praise = [
                'praise' => $num['praise'] +1,
                'past' => $num['past'].','.$this->getUserID()
            ];
        }else{
            $praise = [
                'praise' => $num['praise'] +1,
                'past' =>$this->getUserID()
            ];
        }
        Db::name('article')->where('id',$data['articleID'])->update($praise);
        return Common::rm(1,'操作成功');
    }

    //取消新闻评论点赞
    public function cancel(){
        $data =$this->data;
        $num = DB::view('article','praise,past')->where('id',$data['articleID'])->find();
        if (!$num){
            return Common::rm(-2,'操作失败');
        }
        $a = explode(',',$num['past']);
        foreach ($a as $k => $val){
            if ($val == $this->getUserID()){
                unset($a[$k]);
            }
        }
        $praise = [
            'praise' => $num['praise'] -1,
            'past' =>implode(',',$a)
        ];
        Db::name('article')->where('id',$data['articleID'])->update($praise);
        return Common::rm(1,'操作成功');
    }

    //收藏新闻
    public function collectArticle(){
        $data =$this->data;
        //第一步，判断是否存在该收藏
        $exist = Db::name('collection')->where('userID',$this->getUserID())->find();
        $num = Db::name('article')->where('id',$data['articleID'])->find();
        if ($num['pastc']){
            $a = explode(',',$num['pastc']);
            foreach ($a as $key => $value){
                if ($value == $this->getUserID()){
                    return Common::rm(-2,'请不要重复收藏');
                }
            }
        }else{
            if ($num['pastc']){
                $array = [
                    'collection' => $num['collection']+1,
                    'pastc' =>$num['pastc'].','.$this->getUserID()
                ];
            }else{
                $array = [
                    'collection' => $num['collection']+1,
                    'pastc' =>$this->getUserID()
                ];
            }
            Db::name('article')->where('id',$data['articleID'])->update($array);
        }
        if($exist['userID'] == $this->getUserID()){
            //判断收藏表是否存在数据
            if (!empty($exist['articleID'])){
                //用户已经收藏
                $a = explode(',',$exist['articleID']);
                foreach ($a as $key => $value){
                    if ($value == $data['articleID']){
                        return Common::rm(-2,'请不要重复收藏');
                    }else{
                        $praise = [
                            'articleID' => $exist['articleID'].','.$data['articleID']
                        ];
                        Db::name('collection')->where('userID',$this->getUserID())->update($praise);
                    }
                }
            }else{
                $praise = [
                    'userID' => $this->getUserID(),
                    'articleID' => $data['articleID']
                ];
                Db::name('collection')->where('userID',$this->getUserID())->update($praise);
            }
        }else{
            $praise = [
                'userID' => $this->getUserID(),
                'articleID' => $data['articleID']
            ];
            Db::name('collection')->insert($praise);
        }
        return Common::rm(1,'操作成功');
    }

    //取消新闻收藏
    public function cancelCollect(){
        $data =$this->data;
        $num = DB::name('article')->where('id',$data['articleID'])->find();
        $list = Db::name('collection')->where('userID',$this->getUserID())->find();
        //第一步 删除新闻表里面的数据
        if (!$num & !$list){
            return Common::rm(-2,'操作失败');
        }
        //新闻表数据
        $a = explode(',',$num['pastc']);
        foreach ($a as $k => $val){
            if ($val == $this->getUserID()){
                unset($a[$k]);
            }
        }
        $praise = [
           // 'collection' => $num['collection'] -1,
            'pastc' =>implode(',',$a)
        ];
        //收藏表
        $a = explode(',',$list['articleID']);
        foreach ($a as $k => $val){
            if ($val == $data['articleID']){
                unset($a[$k]);
            }
        }
        $a = [
            'articleID' =>implode(',',$a)
        ];
        Db::name('article')->where('id',$data['articleID'])->update($praise);
        Db::name('collection')->where('userID',$this->getUserID())->update($a);
        return Common::rm(1,'操作成功');
    }

    //新闻与我相关
    public function relatedForMe()
    {
        $userID = $this->getUserID();
        $articleID = Db::name('article_comments')->where('userID',$userID)->whereOr('sendUserID',$userID)->distinct(true)->column('articleID');
        if (!$articleID) {
            return Common::rm(-3,'数据为空');
        }
        $comment = Db::view('article_comments',['id' => 'commentID','parentID','userID','sendUserID','articleID','addtime','content'])
            ->view('article','title,thumb','article.id = article_comments.articleID')
            ->view('operator','name,photo','operator.id = article_comments.userID')
            ->where('articleID','in',$articleID)
            ->where('sendUserID',0)
            ->order('addtime desc')
            ->select();
        if (!$comment) {
            return Common::rm(-3,'数据为空');
        }
        $comments = Db::view('article_comments',['id' => 'commentID','parentID','userID','sendUserID','articleID','addtime','content'])
            ->view('article','title,thumb','article.id = article_comments.articleID')
            ->view(['a_operator' => 'newuser1'],'name,photo','newuser1.id = article_comments.userID')
            ->view(['a_operator'=>'newuser'],['name' => 'sendName','photo' => 'sendPhoto'],'newuser.id = article_comments.sendUserID')
            ->where('articleID','in',$articleID)
            ->order('addtime desc')
            ->select();
        if ($comments) {
            $answer = Db::name('article_comments')->where('articleID','in',$articleID)->field('id,content')->select();
            foreach ($comments as $_key => $_val) {
                foreach ($answer as $__key => $__val) {
                    if ($_val['parentID'] == $__val['id']) {
                        $comments[$_key]['sendContent'] = $__val['content'];
                    }
                }
            }
            foreach ($comments as $key => $val) {
                array_push($comment,$val);
            }
        }
        $ar = [];
        foreach ($comment as $k => $v) {
            $comment[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $ar[]  = $v['addtime'];
        }
        array_multisort($ar,SORT_DESC,$comment);
        $count = $this->data['count'];
        if ($this->data['page'] == 1) {
            $page = 0;
        } else {
            $page = ($this->data['page'] - 1) * $count;
        }
        $comment = array_slice($comment, $page, $count);
        return Common::rm(1,'操作成功',[
            'comment' => $comment
        ]);
    }
}
